<template>
  <el-dialog :title="title" :visible.sync="open" width="70%" append-to-body v-if="open">
    <div class="min-h-screen bg-gray-50 p-6">
      <el-form :model="form" ref="ruleForm">
        <!-- 基本信息卡片 -->
        <el-card class="mb-6 !rounded-button">
          <div class="grid grid-cols-2 gap-4">
            <el-form-item label="派工单号" class="mb-0" prop="orderNo"
              :rules="[{ required: true, message: '请输入邮箱地址', trigger: 'blur' }]">
              <el-input v-model="form.orderNo" />
            </el-form-item>
            <el-form-item label="派工单ID" class="mb-0" prop="orderId"
              :rules="[{ required: true, message: '请输入邮箱地址', trigger: 'blur' }]">
              <el-input v-model="form.orderId" />
            </el-form-item>
          </div>
        </el-card>

        <!-- 物料信息卡片 -->
        <el-card class="mb-6 !rounded-button">
          <template slot="header">
            <div class="flex items-center">
              <span class="font-bold">物料信息</span>
              <el-tooltip content="填写当前派工单涉及的物料信息" placement="top">
                <i class="el-icon-question ml-2"></i>
              </el-tooltip>
            </div>
          </template>
          <div class="grid grid-cols-2 gap-4">
            <el-form-item label="物料编号" prop="materialCode" required
              :rules="[{ required: true, message: '请输入物料编号', trigger: 'blur' }]">
              <el-input v-model="form.materialCode" placeholder="请输入物料编号" />
            </el-form-item>
            <el-form-item label="物料名称" prop="materialName" required
              :rules="[{ required: true, message: '请输入物料名称', trigger: 'blur' }]">
              <el-input v-model="form.materialName" placeholder="请输入物料名称" />
            </el-form-item>
            <el-form-item label="物料规格" prop="materialSpec">
              <el-input v-model="form.materialSpec" placeholder="请输入物料规格" />
            </el-form-item>
            <el-form-item label="物料型号" prop="materialModel">
              <el-input v-model="form.materialModel" placeholder="请输入物料型号" />
            </el-form-item>
          </div>
        </el-card>

        <!-- 任务信息卡片 -->
        <el-card class="mb-6 !rounded-button">
          <template slot="header">
            <div class="flex items-center justify-between">
              <div class="flex items-center">
                <span class="font-bold">任务信息</span>
                <el-tooltip content="填写派工任务相关信息" placement="top">
                  <i class="el-icon-question ml-2"></i>
                </el-tooltip>
              </div>
              <el-button type="primary" size="small" @click="addTask" icon="el-icon-plus">新增任务</el-button>
            </div>
          </template>
          <el-collapse v-model="activeTasks">
            <el-collapse-item v-for="(task, taskIndex) in form.dispatchTask" :key="taskIndex" :name="taskIndex">
              <template slot="title">
                <div class="flex items-center w-full">任务信息
                  <el-button type="danger" size="small" icon="el-icon-delete" class="ml-auto mr-2"
                    @click.stop="removeTask(taskIndex)" />
                </div>
              </template>
              <div class="grid grid-cols-2 gap-4">
                <el-form-item :label="`任务号`" :prop="`dispatchTask[${taskIndex}].taskNo`" required
                  :rules="[{ required: true, message: '请输入任务号', trigger: 'blur' }]">
                  <el-input v-model="task.taskNo" placeholder="请输入任务号" />
                </el-form-item>
                <el-form-item :label="`任务ID`" :prop="`dispatchTask[${taskIndex}].taskId`" required
                  :rules="[{ required: true, message: '请输入任务ID', trigger: 'blur' }]">
                  <el-input v-model="task.taskId" placeholder="请输入任务ID" />
                </el-form-item>
                <el-form-item :label="`工单号`" :prop="`dispatchTask[${taskIndex}].workOrderNo`" required
                  :rules="[{ required: true, message: '请输入工单号', trigger: 'blur' }]">
                  <el-input v-model="task.workOrderNo" placeholder="请输入工单号" />
                </el-form-item>
                <el-form-item :label="`工作中心编号`" :prop="`dispatchTask[${taskIndex}].workCenterCode`" required
                  :rules="[{ required: true, message: '请输入工作中心编号', trigger: 'blur' }]">
                  <el-input v-model="task.workCenterCode" placeholder="请输入工作中心编号" />
                </el-form-item>
                <el-form-item :label="`工作中心名称`" :prop="`dispatchTask[${taskIndex}].workCenterName`" required
                  :rules="[{ required: true, message: '请输入工作中心名称', trigger: 'blur' }]">
                  <el-input v-model="task.workCenterName" placeholder="请输入工作中心名称" />
                </el-form-item>
                <el-form-item :label="`工序编号`" :prop="`dispatchTask[${taskIndex}].processCode`" required
                  :rules="[{ required: true, message: '请输入工序编号', trigger: 'blur' }]">
                  <el-input v-model="task.processCode" placeholder="请输入工序编号" />
                </el-form-item>
                <el-form-item :label="`工序名称`" :prop="`dispatchTask[${taskIndex}].processName`" required
                  :rules="[{ required: true, message: '物料编号', trigger: 'blur' }]">
                  <el-input v-model="task.processName" placeholder="请输入工序名称" />
                </el-form-item>
                <el-form-item label="物料编号" prop="materialCode" required
                  :rules="[{ required: true, message: '请输入物料编号', trigger: 'blur' }]">
                  <el-input v-model="task.materialCode" placeholder="请输入物料编号" />
                </el-form-item>
                <el-form-item label="物料名称" prop="materialName" required
                  :rules="[{ required: true, message: '请输入物料名称', trigger: 'blur' }]">
                  <el-input v-model="task.materialName" placeholder="请输入物料名称" />
                </el-form-item>
                <el-form-item label="物料规格" prop="materialSpec">
                  <el-input v-model="task.materialSpec" placeholder="请输入物料规格" />
                </el-form-item>
                <el-form-item :label="`计划投产时间`" :prop="`dispatchTask[${taskIndex}].planStartTime`" required
                  :rules="[{ required: true, message: '请输入计划投产时间', trigger: 'blur' }]">
                  <el-date-picker v-model="task.planStartTime" type="datetime" placeholder="选择计划投产时间" />
                </el-form-item>
                <el-form-item :label="`计划产出时间`" :prop="`dispatchTask[${taskIndex}].planEndTime`" required
                  :rules="[{ required: true, message: '请输入计划产出时间', trigger: 'blur' }]">
                  <el-date-picker v-model="task.planEndTime" type="datetime" placeholder="选择计划产出时间" />
                </el-form-item>
                <el-form-item :label="`派工数量`" :prop="`dispatchTask[${taskIndex}].dispatchQty`" required
                  :rules="[{ required: true, message: '请输入派工数量', trigger: 'blur' }]">
                  <el-input-number v-model="task.dispatchQty" :min="1" :max="10000" placeholder="请输入派工数量" />
                </el-form-item>

              </div>

              <el-card class="mt-4 !rounded-button">
                <template slot="header">
                  <div class="flex items-center justify-between">
                    <div class="flex items-center">
                      <span class="font-bold">配送信息</span>
                      <el-tooltip content="填写物料配送相关信息" placement="top">
                        <i class="el-icon-question ml-2"></i>
                      </el-tooltip>
                    </div>
                    <el-button type="primary" size="small" @click="addDeliveryInfo(taskIndex)"
                      icon="el-icon-plus">新增配送</el-button>
                  </div>
                </template>
                <el-form-item>
                  <el-table :data="task.deliveryInfo" border>
                    <el-table-column prop="preparationNo" label="备料号" width="120">
                      <template slot-scope="scope">
                        <!-- <el-form-item label="" :prop="'task.deliveryInfo.' + scope.$index + '.preparationNo'" required
                          :rules="[{ required: true, message: '请输入备料号', trigger: 'blur' }]"> -->
                        <el-input v-model="scope.row.preparationNo" placeholder="备料号" />
                        <!-- </el-form-item> -->
                      </template>
                    </el-table-column>
                    <el-table-column prop="materialCode" label="物料编号" width="120">
                      <template slot-scope="{ row }">
                        <el-input v-model="row.materialCode" placeholder="物料编号" />
                      </template>
                    </el-table-column>
                    <el-table-column prop="materialName" label="物料名称" width="150">
                      <template slot-scope="{ row }">
                        <el-input v-model="row.materialName" placeholder="物料名称" />
                      </template>
                    </el-table-column>
                    <el-table-column prop="processName" label="工序名称" width="120">
                      <template slot-scope="{ row }">
                        <el-input v-model="row.processName" placeholder="工序名称" />
                      </template>
                    </el-table-column>
                    <el-table-column prop="workCenterName" label="工作中心" width="120">
                      <template slot-scope="{ row }">
                        <el-input v-model="row.workCenterName" placeholder="工作中心" />
                      </template>
                    </el-table-column>
                    <el-table-column prop="requiredQty" label="所需数量" width="180">
                      <template slot-scope="{ row }">
                        <el-input-number v-model="row.requiredQty" :min="1" :max="10000" size="mini" />
                      </template>
                    </el-table-column>
                    <el-table-column prop="planTime" label="计划时间" width="200">
                      <template slot-scope="{ row }">
                        <el-date-picker v-model="row.planTime" type="datetime" placeholder="选择计划时间" size="mini" />
                      </template>
                    </el-table-column>
                    <el-table-column prop="deliveryPosName" label="配送位置" width="120">
                      <template slot-scope="{ row }">
                        <el-input v-model="row.deliveryPosName" placeholder="配送位置" />
                      </template>
                    </el-table-column>
                    <el-table-column label="操作" width="80">
                      <template slot-scope="{ $index }">
                        <el-button type="danger" size="small" icon="el-icon-delete" circle
                          @click="removeDeliveryInfo(taskIndex, $index)" />
                      </template>
                    </el-table-column>
                  </el-table>
                </el-form-item>
              </el-card>
            </el-collapse-item>
          </el-collapse>
        </el-card>
      </el-form>
      <!-- 操作按钮 -->
      <div class="fixed bottom-0 left-0 right-0 bg-white p-4 shadow-md">
        <div class="flex justify-center space-x-4">
          <el-button type="primary" class="!rounded-button whitespace-nowrap" @click="submitForm">提交</el-button>
          <el-button class="!rounded-button whitespace-nowrap" @click="cancel">取消</el-button>
        </div>
      </div>
    </div>
  </el-dialog>
</template>
<script>
import { productionPlanSave, productionPlanDetails } from "@/api/lineProduction/index"

export default {
  data() {
    return {
      open: false,
      title: '新增',

      activeTasks: [0],
      form: {
        orderId: '',
        orderNo: '',
        materialId: '',
        materialCode: '',
        materialName: '',
        materialSpec: '',
        materialModel: '',
        dispatchTask: [
          {
            taskId: '',
            taskNo: '',
            workOrderProcessId: '',
            workOrderNo: '',
            workCenterId: '',
            workCenterCode: '',
            workCenterName: '',
            processId: '',
            processCode: '',
            processName: '',
            materialId: '',
            materialCode: '',
            materialName: '',
            materialModel: '',
            planStartTime: '',
            planEndTime: '',
            dispatchQty: 0,
            // taskStatus: '待派工',
            createdAt: '',
            modifiedAt: '',
            deliveryInfo: [
              {
                preparationNo: '',
                materialId: '',
                materialCode: '',
                materialName: '',
                materialSpec: '',
                materialModel: '',
                materialDesc: '',
                processId: '',
                processCode: '',
                processName: '',
                workCenterId: '',
                workCenterCode: '',
                workCenterName: '',
                requiredQty: 0,
                planTime: '',
                batchNo: '',
                serialNo: '',
                deliveryPosId: '',
                deliveryPosCode: '',
                deliveryPosName: ''
              }
            ]
          }
        ]
      },
      rules: {
        orderId: [{ required: true, message: '请输入派工单号', trigger: 'blur' }],
        orderNo: [{ required: true, message: '请输入派工ID', trigger: 'blur' }],
        materialCode: [{ required: true, message: '请输入物料编号', trigger: 'blur' }],
        materialName: [{ required: true, message: '请输入物料名称', trigger: 'blur' }],
      }
    }
  },
  methods: {
    add() {
      this.open = true
      this.title = '新增'
      this.form = {
        orderId: '',
        orderNo: '',
        materialId: '',
        materialCode: '',
        materialName: '',
        materialSpec: '',
        materialModel: '',
        dispatchTask: [
          {
            taskId: '',
            taskNo: '',
            workOrderProcessId: '',
            workOrderNo: '',
            workCenterId: '',
            workCenterCode: '',
            workCenterName: '',
            processId: '',
            processCode: '',
            processName: '',
            materialId: '',
            materialCode: '',
            materialName: '',
            materialModel: '',
            planStartTime: '',
            planEndTime: '',
            dispatchQty: 0,
            // taskStatus: '待派工',
            createdAt: '',
            modifiedAt: '',
            deliveryInfo: [
              {
                preparationNo: '',
                materialId: '',
                materialCode: '',
                materialName: '',
                materialSpec: '',
                materialModel: '',
                materialDesc: '',
                processId: '',
                processCode: '',
                processName: '',
                workCenterId: '',
                workCenterCode: '',
                workCenterName: '',
                requiredQty: 0,
                planTime: '',
                batchNo: '',
                serialNo: '',
                deliveryPosId: '',
                deliveryPosCode: '',
                deliveryPosName: ''
              }
            ]
          }
        ]
      }
    },
    edit(record) {
      this.open = true
      this.title = '编辑'

      productionPlanDetails({ id: record.id }).then(res => {
        console.log('编辑', res)
        this.form = JSON.parse(JSON.stringify(res.data))
      })
    },
    addTask() {
      const newTaskNo = `T${new Date().getFullYear()}${String(new Date().getMonth() + 1).padStart(2, '0')}${String(new Date().getDate()).padStart(2, '0')}${String(this.form.dispatchTask.length + 1).padStart(3, '0')}`;
      this.form.dispatchTask.push({
        taskId: ``,
        taskNo: newTaskNo,
        workOrderProcessId: '',
        workOrderNo: ``,
        workCenterId: '',
        workCenterCode: '',
        workCenterName: '',
        processId: '',
        processCode: '',
        processName: '',
        materialId: '',
        materialCode: '',
        materialName: '',
        materialModel: '',
        planStartTime: '',
        planEndTime: '',
        dispatchQty: 1,
        // taskStatus: '待派工',
        createdAt: '',
        modifiedAt: '',
        deliveryInfo: []
      });
      this.activeTasks.push(this.form.dispatchTask.length - 1);
    },
    removeTask(index) {
      this.form.dispatchTask.splice(index, 1);
      this.activeTasks = this.activeTasks.filter(i => i !== index).map(i => i > index ? i - 1 : i);
    },
    addDeliveryInfo(taskIndex) {
      this.form.dispatchTask[taskIndex].deliveryInfo.push({
        preparationNo: ``,
        materialId: '',
        materialCode: '',
        materialName: '',
        materialSpec: '',
        materialModel: '',
        materialDesc: '',
        processId: '',
        processCode: '',
        processName: '',
        workCenterId: '',
        workCenterCode: '',
        workCenterName: '',
        requiredQty: 1,
        planTime: '',
        batchNo: '',
        serialNo: '',
        deliveryPosId: '',
        deliveryPosCode: '',
        deliveryPosName: ''
      });
    },
    removeDeliveryInfo(taskIndex, deliveryIndex) {
      this.form.dispatchTask[taskIndex].deliveryInfo.splice(deliveryIndex, 1);
    },
    submitForm() {
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
        //   console.log(99999,this.form.dispatchTask.some(item => item.deliveryInfo.some(detail => detail.materialName == ''))
        // )
          const preparationNo = this.form.dispatchTask.some(item => item.deliveryInfo.some(detail => detail.preparationNo == ''));//备料号

          const materialCode = this.form.dispatchTask.some(item => item.deliveryInfo.some(detail => detail.materialCode == ''));//物料编号
          const materialName = this.form.dispatchTask.some(item => item.deliveryInfo.some(detail => detail.materialName == ''))//物料名称

          const processName = this.form.dispatchTask.some(item => item.deliveryInfo.some(detail => detail.processName == ''));//工序名称

          const workCenterName = this.form.dispatchTask.some(item => item.deliveryInfo.some(detail => detail.workCenterName == ''));//工序名称

          // const workCenterName = this.form.dispatchTask.some(item => item.deliveryInfo.some(detail => detail.workCenterName == ''));//工序名称

          if(preparationNo){
            return  this.$message.error('请填写备料号');
          }
          // if(materialId){
          //   return  this.$message.error('请填写备料号');
          // }
          if(materialCode){
            return  this.$message.error('请填写物料编码');
          }
          if(materialName){
            return  this.$message.error('请填写物料名称');
          }
          if(processName){
            return  this.$message.error('请填写工序名称');
          }
          if(workCenterName){
            return  this.$message.error('请填写工作中心名称');
          }

          productionPlanSave(this.form).then(res => {
            console.log(99999, res)
            this.open = false
            this.$emit('ok')
          })
        } else {
          console.log('error submit!!');
          return false;
        }
      });
      console.log('提交数据:', this.form);
    },
    saveDraft() {
      this.$message.success('草稿保存成功');
      console.log('保存草稿:', this.form);
    },
    cancel() {
      this.open = false
      this.$emit('ok')
    }
  }
}
</script>
<style scoped>
.el-card {
  margin-bottom: 20px;
}

.el-form-item {
  margin-bottom: 18px;
}

.el-collapse-item__header {
  font-weight: 500;
}

.el-table {
  margin-top: 10px;
}

.fixed-bottom {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: white;
  padding: 16px;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
  z-index: 1000;
}
</style>
